import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

import byzw
from UI.Ui_MainWindow import MainWindow
from UI.Ui_Progress import DProgress


class Window:
    def __init__(self):
        self.ui = MainWindow()
        self.initUI()
        self.books = []
        self.chapters = []
        self.progress = 0

    def initUI(self):
        # with open("UI/BigSur_White.qss", "r") as f:
        #     qss = f.read()
        # self.ui.setStyleSheet(qss)

        self.ui.book_list.setVisible(False)
        self.ui.btn_refresh.clicked.connect(self.refresh)
        self.ui.book_list.itemClicked.connect(self.jmp_book)
        self.ui.btn_jump.clicked.connect(self.locate_chapter)
        self.ui.btn_locate_page_1.clicked.connect(self.locate_page_1)

        self.ui.btn_download_all.clicked.connect(self.download_all)


    def set_window_center(self, window):
        screen = QDesktopWidget().screenGeometry()
        size = window.geometry()
        t = int((screen.height() - size.height()) / 2 - 40)
        l = int((screen.width() - size.width()) / 2)
        window.move(l, t)

    def test(self):
        print("Hello, world!")
        # print(self.ui.book_list.currentRow())

    def refresh(self):
        self.books = []
        self.ui.book_list.setVisible(True)

        h = self.ui.btn_refresh.height() + self.ui.book_list.height() + 100
        self.ui.animation = QPropertyAnimation(self.ui.centralwidget, b'geometry')
        self.ui.animation.setDuration(500)
        self.ui.animation.setStartValue(QRect(self.ui.centralwidget.x(), self.ui.centralwidget.y(), 600, 150))
        self.ui.animation.setEndValue(QRect(self.ui.centralwidget.x(), self.ui.centralwidget.y(), 600, h))
        self.ui.animation.start()

        self.ui.stackw_1.resize(600, h)

        surl = self.ui.combobox_surl.currentText()
        self.books = byzw.get_books(surl)
        if not self.books:
            return False
        for book in self.books:
            self.ui.book_list.addItem(book['title'])

    def jmp_book(self):
        self.chapters = []
        # print(self.ui.book_list.currentRow())
        self.ui.label2.setText(self.books[self.ui.book_list.currentRow()]['title'])

        burl = self.books[self.ui.book_list.currentRow()]['link']
        self.chapters = byzw.get_chapters(burl)

        for chapter in self.chapters:
            self.ui.chapter_list.addItem(chapter['title'])
        self.ui.stackw_1.setCurrentIndex(1)
        self.ui.label3.setText('/' + str(len(self.chapters) - 1))

    def locate_chapter(self):
        row = int(self.ui.lineEdit_jump.text())
        if not row:
            QMessageBox.information(self.ui, u'提示', u'请先输入')
            return False
        if row > len(self.chapters):
            QMessageBox.information(self.ui, u'提示', u'超出范围')
            self.ui.lineEdit_jump.clear()
            return False
        item = self.ui.chapter_list.item(row)
        self.ui.chapter_list.scrollToItem(item)
        self.ui.lineEdit_jump.clear()

    def locate_page_1(self):
        self.chapters = []
        self.ui.chapter_list.clear()
        self.ui.stackw_1.setCurrentIndex(0)

    def download_all(self):
        dirname = self.ui.label2.text()
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        os.chdir(dirname)
        self.ui.progressbar = DProgress()
        self.ui.progressbar.show()
        self.ui.progressbar.progress.setValue(20)
        time.sleep(3)
        # self.ui.progressbar.setEnabled(True)
        # self.ui.progressbar.setVisible(True)
        # self.ui.progressbar.setRange(0, len(self.chapters))
        # self.ui.progressbar.show()
        indexs = [x for x in range(len(self.chapters))]

        # self.ui.progressbar.setValue(20)
        # with ThreadPoolExecutor(max_workers=8) as executor:
        #     executor.map(self.download, indexs)
        for index in indexs:
            self.download(index)
            self.ui.progressbar.progress.setValue(index+1)
            if index + 1 == len(self.chapters):
                self.ui.progressbar.setVisible(False)
                QMessageBox.information(self.ui, u'提示', u'下载完成')

    def download(self, index):
        chapter = self.chapters[index]
        title = chapter['title']
        link = chapter['link']
        fname = title + '.txt'
        content = byzw.get_content(link).replace('<br>', '\n').replace('&nbsp;', ' ').replace('/p>', '')

        with open(fname, 'w') as f:
            f.write(title + '\n' + content)
        print("{} 下载完成".format(title))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.ui.show()
    sys.exit(app.exec_())
